package com.alone.mybatisplus.datascope.core;

import com.alone.mybatisplus.datascope.core.domain.DataScope;
import com.alone.mybatisplus.datascope.core.domain.ModelDataScope;
import com.alone.mybatisplus.datascope.core.loader.DataScopeLoader;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * @author Alone
 */
@Slf4j
@RequiredArgsConstructor
public class DataScopeInnerInterceptor implements InnerInterceptor {

    private final DataScopeLoader loader;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds,
                            ResultHandler resultHandler, BoundSql boundSql) {
        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
        String originalSql = boundSql.getSql();
        Object parameterObject = boundSql.getParameterObject();

        DataScope dataScope = DataScopeExtractor.findDataScope(parameterObject, ms);

        if (dataScope.isAllowAll()) {
            return;
        }

        if (dataScope instanceof ModelDataScope) {
            ModelDataScope modelDataScope = (ModelDataScope) dataScope;
            if (MainScopeContext.needHandle(modelDataScope.getModel())) {
                loader.loadFilterValue(modelDataScope);
            } else {
                return;
            }
        }

        mpBs.sql(dataScope.getRenderedSql(originalSql));
    }


}
